package top.anydata.lifeofcode.lifesystem.web.requests.api;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.WriteListener;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpServletResponseWrapper;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

/**
 * 功能描述:
 *
 * @author <a href="mailto:caingao@anydata.top">CainGao</a>
 * @version V_1.0
 * @date 2024/5/9 3:47 PM
 */
public class AppResponseWrapper extends HttpServletResponseWrapper {
    private ByteArrayOutputStream bos = new ByteArrayOutputStream();

    public AppResponseWrapper(HttpServletResponse response) {
        super(response);
    }
    @Override
    public PrintWriter getWriter() throws IOException {
        return new PrintWriter(bos, true);
    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        return new ServletOutputStream() {
            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setWriteListener(WriteListener writeListener) {

            }

            @Override
            public void write(int b) throws IOException {
                bos.write(b);
            }

            // 需要实现的其他方法，例如write(byte[])等，可以根据需要添加
        };
    }

    // 获取响应体内容作为字符串
    public String getContent() {
        return bos.toString(StandardCharsets.UTF_8);
    }

    // 获取响应体内容作为字节数组，可能用于加密
    public byte[] getByteArray() {
        return bos.toByteArray();
    }


}
